// pages/user/dingdanDetail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    types: 0,//类型
    status: 0,//状态
    statusStr: "",//状态str
    remainTime: "暂无",//剩余时间str
    orderId: 0,//订单ID
    orderDetail: [],//订单详情
    imageUrl: app.d.imageUrlFix,//图片地址
    itemData: {},
    isRefresh: 0,
    orderAmount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 页面跳转字段赋值
    this.setData({
      status: parseInt(options.status),
      types: parseInt(options.types),
      orderId: parseInt(options.orderId),
    });

    this.queryOrderDetail();

    if (this.data.status == 0) {
      this.setData({
        statusStr: "等待买家付款"
      });
    } else if (this.data.status == 1) {
      this.setData({
        statusStr: "等待卖家发货"
      });
    } else if (this.data.status == 2) {
      this.setData({
        statusStr: "卖家已发货"
      });
    } else if (this.data.status == 3) {
      this.setData({
        statusStr: "订单已完成"
      });
    } else if (this.data.status == 4) {
      this.setData({
        statusStr: "退货"
      });
    }
  },

  /**
   * 查询订单详情
   */
  queryOrderDetail: function (e) {
    var that = this;
    var orderId = that.data.orderId;
    var total = 0;
    app.request("WxOrderListService", "queryOrderDetail", { orderId: orderId }, function (data) {
      if (data.orderDetail.orderGoodsList != null && data.orderDetail.orderGoodsList.length > 0) {
        for (let i = 0; i < data.orderDetail.orderGoodsList.length; i++) {
          total += data.orderDetail.orderGoodsList[i].goods_number;
        }
        data.orderDetail["totalAmount"] = total;
      }

      that.setData({
        orderDetail: data.orderDetail,
        orderAmount: data.orderDetail.order_amount
      });
    });
  },

  /**
 * 删除订单
 */
  delOrder: function (e) {
    var that = this;
    var orderId = e.currentTarget.dataset.orderid;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];//上个界面
    wx.showModal({
      title: '提示',
      content: '您确定要删除订单吗？',
      success: function (res) {
        res.confirm && app.request("WxOrderListService", "modOrderStatus", { id: orderId, type: 'delete' }, function (data) {
          wx.showToast({
            title: '删除成功！',
            duration: 2000
          });
          prevPage.setData({
            isRefresh: 1,
          });
          wx.navigateBack();
        });
      }
    });
  },

  //取消订单
  removeOrder: function (e) {
    var that = this;
    var orderId = e.currentTarget.dataset.orderid;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];//上个界面
    wx.showModal({
      title: '提示',
      content: '你确定要取消订单吗？',
      success: function (res) {
        res.confirm && app.request("WxOrderListService", "modOrderStatus", { id: orderId, type: 'cancel' }, function (data) {
          wx.showToast({
            title: '操作成功！',
            duration: 2000
          });
          prevPage.setData({
            isRefresh: 1,
          });
          wx.navigateBack();
        });
        // res.confirm && wx.request({
        //   url: app.d.ceshiUrl + '/Api/Order/orders_edit',
        //   method:'post',
        //   data: {
        //     id: orderId,
        //     type:'cancel',
        //   },
        //   header: {
        //     'Content-Type':  'application/x-www-form-urlencoded'
        //   },
        //   success: function (res) {
        //     //--init data
        //     var status = res.data.status;
        //     if(status == 1){
        //       wx.showToast({
        //         title: '操作成功！',
        //         duration: 2000
        //       });
        //       that.loadOrderList();
        //     }else{
        //       wx.showToast({
        //         title: res.data.err,
        //         duration: 2000
        //       });
        //     }
        //   },
        //   fail: function () {
        //     // fail
        //     wx.showToast({
        //       title: '网络异常！',
        //       duration: 2000
        //     });
        //   }
        // });

      }
    });
  },

  // 弹窗
  setModalStatus: function (e) {
    // wx.navigateTo({
    //   url: '../order/pay?order=' + JSON.stringify(order),
    // })
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })

    this.animation = animation
    animation.translateY(300).step();

    this.setData({
      animationData: animation.export()
    })

    if (e.currentTarget.dataset.status == 1) {

      this.setData(
        {
          showModalStatus: true
        }
      );
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200);

    console.log(e.currentTarget.dataset.order);
    var order = e.currentTarget.dataset.order;
    this.setData({
      itemData: order
    })
  },

  /** 
   * 确定付款
   */
  payOrder: function (e) {
    var that = this;
    wx.showLoading({
      title: '数据加载中',
    });
    var orderId = that.data.orderId;
    app.request("WxPaymentController", "getPayParam", {
      openid: app.globalData.userInfo['openid'],
      orderId: orderId,
      orderAmount: that.data.orderAmount,
    },
      function (data) {
        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign,
          'success': function (res) {
            app.request("WxPaymentController", "orderQuery", {
              orderId: orderId
            }, function (data) {
              wx.hideLoading();
              wx.showToast({
                title: '操作成功',
                duration: 2000,
              });
              app.request("WxOrderListService", "modOrderStatus", {
                id: orderId,
                type: 'confirmPay',
                orderAmount: that.data.orderAmount,
              }, function (data) {
                that.setData({
                  showModalStatus: false,
                })
                wx.redirectTo({
                  url: '../user/dingdanDetail?status=1&types=1&orderId=' + orderId,
                })
              });

            }, function (data) {
              wx.hideLoading();
              wx.showToast({
                title: "数据更新失败！",
                duration: 2000,
              });
              that.setData({
                showModalStatus: false,
              })
              return false;
            }); 
          }, 
          'fail': function (res) {
            wx.hideLoading();
            wx.showToast({
              title: "支付失败",
              duration: 2000,
            });
            that.setData({
              showModalStatus: false,
            })
          }
        })
        
      });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //刷新界面
    if (that.data.isRefresh == 1) {
      that.queryOrderDetail();
      wx.showToast({
        title: '操作成功',
        duration: 2000,
      });
      that.setData({
        isRefresh: 0,
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
      var data = new Date();
      var shared = data.getTime()+"";
      var shareId = shared.substring(8, shared.length) + app.d.userId;
      return {
          title: '大肚商城',
          path: '/pages/index/index?duid=' + app.d.userId + "&shareId=" + shareId,
          success: function(res) {
              app.request("DistributorService", "shareLog", {
                  uid: app.d.userId,
                  shareId: shareId,
              }, function(data){
                  // 分享成功
                  console.log(res);
              })
          },
          fail: function(res) {
              // 分享失败
              console.log(res);
          }
      }
  }
})